import { useContext } from 'react'
import '../../7_0_redux/index.css'
import ProfileSetting from './ProfileSetting'
import { createContext } from '../../8_hooks/2_sources/5_useContext';
// import { useReducer } from 'react';
import { useReducer } from '../../8_hooks/2_sources/6_useReducer';

export const settingContext = createContext();

// 好像此处设置的initState没有效果，只有useReducer中设置的init才有效果
const settingReducer = (preState = {
    username: '张三',
    unReadCount: 5,
}, action) => {

    const { type, payload } = action;
    console.log("type", type, payload);

    switch (type) {
        case 'setUsername':
            return { ...preState, username: payload }
        case 'setUnReadCount':
            return { ...preState, unReadCount: payload }
        default:
            console.log("preSatate", preState);

            return preState;
    }
}

export default function Demo() {
    const [state, dispatch] = useReducer(settingReducer, {
        username: '张三',
        unReadCount: 5,
    })

    return <>
        <settingContext.Provider value={{
            username: state.username,
            unReadCount: state.unReadCount,
            dispatch,
        }}>
            <Header />
            <Setting />
        </settingContext.Provider>

        <p>
            1. useReducer相比useState，就是多了一层action的处理。 <br />
            2. 代码实际上写的更多了，但是好处就是可以集中管理state，而不是分散在各个组件中。
        </p>
    </>;
}

function Header() {
    const { username, unReadCount } = useContext(settingContext);
    return (
        <div className='header'>
            <span>{username}</span>
            <span className='un-read'>
                未读
                <div className='un-read-num'>{unReadCount}</div>
            </span>
        </div>
    )
}

function Setting() {
    return (
        <div className='setting'>
            设置页面：
            <ProfileSetting />
        </div>
    );
}

